package vip.denglei.company.service;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import vip.denglei.company.mapper.WorkWechatMsgContextMapper;
import vip.denglei.company.mapper.WorkWechatMsgInfoMapper;
import vip.denglei.company.mapper.WorkWechatRegularTaskMapper;
import vip.denglei.company.mapper.WorkWechatTaskManageMapper;
import vip.denglei.company.model.WorkWechatMsgContext;
import vip.denglei.company.model.WorkWechatMsgInfo;
import vip.denglei.company.model.WorkWechatRegularTask;
import vip.denglei.company.model.WorkWechatTaskManage;
import vip.denglei.company.model.weather.Casts;
import vip.denglei.company.model.weather.Weather;
import vip.denglei.company.model.workwechat.AccessToken;
import vip.denglei.company.model.workwechat.DeptUser;
import vip.denglei.company.model.workwechat.UseridList;
import vip.denglei.company.model.workwechat.dk.Base_info;
import vip.denglei.company.model.workwechat.dk.Datas;
import vip.denglei.company.model.workwechat.dk.DkInfo;
import vip.denglei.company.util.DateUtils;
import vip.denglei.company.util.HttpClientUtil;
import vip.denglei.company.util.JsonUtils;
import vip.denglei.company.util.WorkWechatSendMsgUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TasksService {

    protected static Logger logger= LoggerFactory.getLogger(TasksService.class);
    @Autowired
    private WorkWechatRegularTaskMapper workWechatRegularTaskMapper;
    @Autowired
    public  WorkWechatMsgInfoMapper workWechatMsgInfoMapper;
    @Autowired
    public  WorkWechatMsgContextMapper workWechatMsgContextMapper;
    @Autowired
    public WorkWechatTaskManageMapper workWechatTaskManageMapper;

    /*
        晚上任务
     */
    @Scheduled(cron = "0 30 21 * * 0-7")
    public void sendPushNight(){
        sendWeather();//每天发送天气-动态
        staicAiPush(1);
    }

    /*
     *其他时间的定时任务
     */
    @Scheduled(cron = "0 00 14 * * 0-7")
    public void sendOther()   {
        taskReport();//周报
    }


   /*
     *白天任务
     */
    @Scheduled(cron = "0 00 9 * * 1-6")
    public void sendPushDay()   {
        //每天发送打卡记录-动态
        try {
            sendZSDK();//发送打卡记录
        } catch (ParseException e) {
            e.printStackTrace();
        }
       // pushTask();
        staicAiPush(0);
    }

    @Scheduled(cron = "0 00 9 * * 1-1")
    public void sendPushDay2()   {
        //每周一发一次
        pushTask();

    }
    /**
     * 静态内容智能推送
     * @param pushTime
     */
    private void staicAiPush(int pushTime){
        long current = System.currentTimeMillis();
        Date currentDate = new Date(current);
        int whatWeekDay =DateUtils.whatWeekDay(currentDate);
        int moonDay=DateUtils.getDate(currentDate);
        List<WorkWechatRegularTask> list=workWechatRegularTaskMapper.getList();
        for (int i=0;i<list.size();i++){
            WorkWechatRegularTask workWechatRegularTask=list.get(i);
            if (workWechatRegularTask.getPushTime()!=pushTime){
                continue;
            }
            if(workWechatRegularTask.getRepeatDay()==0){
                WorkWechatSendMsgUtils.sendMsg(workWechatRegularTask.getUserIdList(),workWechatRegularTask.getContext());
            }
            if (!workWechatRegularTask.getRepeatWeek().equals("0")){
                String week=workWechatRegularTask.getRepeatWeek();
                String temp[]=week.split(",");
                for (int j=0;j<temp.length;j++){
                    //logger.debug("今天周"+whatWeekDay+"vs"+temp[j]);
                    if ((whatWeekDay+"").equals(temp[j])){
                        WorkWechatSendMsgUtils.sendMsg(workWechatRegularTask.getUserIdList(),workWechatRegularTask.getContext());
                    }
                }
            }

            if (!workWechatRegularTask.getRepeatMoon().equals("0")){
                String moon=workWechatRegularTask.getRepeatMoon();
                String temp[]=moon.split(",");
                //logger.debug("月："+temp.toString());
                for (int j=0;j<temp.length;j++){
                    //logger.debug("今天月"+moonDay+"vs"+temp[j]);
                    if ((moonDay+"").equals(temp[j])){
                        WorkWechatSendMsgUtils.sendMsg(workWechatRegularTask.getUserIdList(),workWechatRegularTask.getContext());
                    }
                }
            }

        }
    }
    //-------------周期性动态任务汇报
    private  void taskReport(){
        {
            long current = System.currentTimeMillis();
            Date currentDate = new Date(current);
            long now=0;
            try {
                now=DateUtils.unixTimeFormat(DateUtils.dateFormat(currentDate,DateUtils.DATE_TIME_PATTERN));
            } catch (ParseException e) {
                e.printStackTrace();
                return;
            }
            int whatWeekDay =DateUtils.whatWeekDay(currentDate);
            int moonDay=DateUtils.getDate(currentDate);
            long dayUnix=86400;
            long hour=3600;
            if (whatWeekDay==6){
                List<WorkWechatTaskManage> list=workWechatTaskManageMapper.getOkTaskList(now-(dayUnix*4+hour*21),now);
                if (list.size()==0||list==null){
                    return;
                }
                String temp="本周公司任务周报：";
                for (int i=0;i<list.size();i++){
                    WorkWechatTaskManage workWechatTaskManage=list.get(i);
                    String ok=DateUtils.dateFormat(list.get(i).getCompleteTime());
                    String isExpand="未延期";
                    if(workWechatTaskManage.getExpandTime()-workWechatTaskManage.getEndTime()>0){
                        isExpand="已延期";
                    }
                    temp=temp+"\n【"+list.get(i).getTaskName()+"】"+"，完成时间："+ok+"，是否延期："+isExpand;
                    //logger.debug(temp);
                }
                WorkWechatSendMsgUtils.setBotMsg(temp,1,1,workWechatMsgInfoMapper,workWechatMsgContextMapper);
            }
            if (moonDay==30){
                {
                    List<WorkWechatTaskManage> list=workWechatTaskManageMapper.getOkTaskList(now-(dayUnix*29+hour*21),now);
                    if (list.size()==0||list==null){
                        return;
                    }
                    String temp="本月公司任务月报：";
                    for (int i=0;i<list.size();i++){
                        WorkWechatTaskManage workWechatTaskManage=list.get(i);
                        String ok=DateUtils.dateFormat(list.get(i).getCompleteTime());
                        String isExpand="未延期";
                        if(workWechatTaskManage.getExpandTime()-workWechatTaskManage.getEndTime()>0){
                            isExpand="已延期";
                        }
                        temp=temp+"\n【"+list.get(i).getTaskName()+"】"+"，完成时间："+ok+"，是否延期："+isExpand;
                    }
                    WorkWechatSendMsgUtils.setBotMsg(temp,1,1,workWechatMsgInfoMapper,workWechatMsgContextMapper);
                }
                }

            }

        }





    //-----高德天气查询相关
    /**
     * 高德天气接口
     */
    private  final String GD_WEATHER="https://restapi.amap.com/v3/weather/weatherInfo?parameters";
    /**
     * 高德查询的key
     */
    private  final String GD_kEY="a26d2cf8fefb3121e7f6151c3a5e5803";
    /**
     * 发送天气
     */
    private void sendWeather(){
        Map<String, String> param=new HashMap<>();
        param.put("key",GD_kEY);
        param.put("city","422802");
        param.put("extensions","all");
        String json= HttpClientUtil.doGet(GD_WEATHER,param );
        Weather weather= JsonUtils.jsonToPojo(json,Weather.class);
        String temp="利川天气：";
        for (int i=1;i<weather.getForecasts().get(0).getCasts().size();i++){
            Casts casts=weather.getForecasts().get(0).getCasts().get(i);
             temp=temp+"\n"+casts.getDate()+"：\n"+"白天 "+casts.getDayweather()+" "+casts.getDaytemp()+"°C"+"\n夜间 "+casts.getNightweather()+" "+casts.getNighttemp()+"°C";
        }
        //logger.debug(temp);
        WorkWechatSendMsgUtils.setBotMsg(temp,1,1,workWechatMsgInfoMapper,workWechatMsgContextMapper);
    }
    //---------企业微信二次开发通用封装
    /**
     * 企业ID
     */
    private  final String WORK_WECHAT_COMPANY_ID="wwc846e11b754ed19a";


    /**
     * 获取企业微信token
     * @param corpsecret 应用的凭证密钥
     * @return
     */
    private String getToken(String corpsecret){
        String url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+WORK_WECHAT_COMPANY_ID+"&corpsecret="+corpsecret;
        String json= HttpClientUtil.doGet(url);
        AccessToken accessToken=JsonUtils.jsonToPojo(json, AccessToken.class);
        return accessToken.getAccess_token();
    }



    /**
     * 打卡ID
     */
    private final String WORK_WECHAT_DK_ID="A4DcKBcACliATb1Hb35C50DxKyMS1b13j9nopZ1OnRA";

    /**
     * 通讯录ID,通讯录有ip白名单，出现问题先看下ip
     */
    private final String WORK_WECHAT_TXL_ID="pgkvnWNMRoBjh0ef8rpbSR0Om_fp3qtUSTSX7Pi1HRk";


    /**
     * 获取成员id列表
     * @return
     */
    private UseridList getTxlBmcy(){
        String token=getToken(WORK_WECHAT_TXL_ID);
        String url="https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token="+token;
        String json= HttpClientUtil.doGet(url);
        UseridList useridList=JsonUtils.jsonToPojo(json,UseridList.class);
        if(useridList==null)
            return null;
        return useridList;
    }
    /*
     *发送昨日打卡记录
     */
    public void sendZSDK() throws ParseException {
        UseridList useridList = getTxlBmcy();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_daydata?debug=1&access_token=" + getToken(WORK_WECHAT_DK_ID);
        Date d=new Date(System.currentTimeMillis()-1000*60*60*24);
        SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
        String ZUOTIAN=sp.format(d);//获取昨天日期
        JSONObject param = new JSONObject();
        param.put("starttime", DateUtils.unixTimeFormat(ZUOTIAN+" 00:00:00"));
        param.put("endtime", DateUtils.unixTimeFormat(ZUOTIAN+" 23:59:59"));
        List<DeptUser> deptUsers = useridList.getDept_user();
        List<String> userlist=new ArrayList<>();
        for (int i=0;i<deptUsers.size();i++){
            userlist.add(deptUsers.get(i).getUserid());
        }
        param.put("useridlist", userlist);
        String json = HttpClientUtil.doPostJson(url, param.toString());
        DkInfo dkInfo=JSONObject.parseObject(json,DkInfo.class);
        if (dkInfo==null){
            return;
        }
        List<Datas> datasList=dkInfo.getDatas();
        String temp="昨日打卡汇总："+"\n";
        for (int i=0;i<datasList.size();i++){
            Base_info baseInfo=datasList.get(i).getBase_info();
            long time=datasList.get(i).getBase_info().getDate();
            long btime=datasList.get(i).getSummary_info().getEarliest_time()+time;
            long wtime=datasList.get(i).getSummary_info().getLastest_time()+time;
            if (i==datasList.size()-1){
                temp=temp+baseInfo.getName()+"-"+baseInfo.getRule_info().getGroupname()+"-"+DateUtils.dateFormat(time)+" 上班："+DateUtils.dateFormatTime(btime)+" 下班"+DateUtils.dateFormatTime(wtime);
            }else {
                temp=temp+baseInfo.getName()+"-"+baseInfo.getRule_info().getGroupname()+"-"+DateUtils.dateFormat(time)+" 上班："+DateUtils.dateFormatTime(btime)+" 下班"+DateUtils.dateFormatTime(wtime)+"\n";
            }
        }

        // setBotMsg(temp,1,1);//测试环境群
        WorkWechatSendMsgUtils.setBotMsg(temp,1,3,workWechatMsgInfoMapper,workWechatMsgContextMapper);
    }
    //---------------------每天任务提醒
    private void pushTask(){
        List<WorkWechatTaskManage> list=workWechatTaskManageMapper.getTaskList();
        if (list.size()==0||list==null){
            return;
        }
        String temp="每日任务提醒：";
        long current = System.currentTimeMillis();
        Date currentDate = new Date(current);
        String time="";
        try {
            time=DateUtils.dateFormat(currentDate,"yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        for (int i=0;i<list.size();i++){
            WorkWechatTaskManage model=list.get(i);
            temp=temp+"\n"+"【"+model.getTaskName()+"】的截止日期："+DateUtils.dateFormat(model.getExpandTime())+",干系人："+model.getTaskWorker();
            long ltime=0;
            try {
                ltime= DateUtils.unixTimeFormat(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long tempTime=model.getExpandTime()-ltime;
            if(tempTime<=0){
                String ding="任务【"+model.getTaskName()+"】已经逾期，"+"请提醒下："+model.getTaskWorker();
                WorkWechatSendMsgUtils.sendMsg(model.getTaskWorkerId(),"你的任务【"+model.getTaskName()+"】已经逾期，请与任务发布者沟通情况。");
                WorkWechatSendMsgUtils.setBotMsg(ding,1,3,workWechatMsgInfoMapper,workWechatMsgContextMapper);
                WorkWechatSendMsgUtils.sendMsg("CY0006",ding);
            }
            if (tempTime>0&&tempTime<172800){//unix时间为2天
                String ding="任务【"+model.getTaskName()+"】不足48小时，"+"请提醒下："+model.getTaskWorker();
                WorkWechatSendMsgUtils.sendMsg(model.getTaskWorkerId(),"你的任务【"+model.getTaskName()+"】不足48小时，请注意结束时间，若有问题可找邓磊协助。");
                WorkWechatSendMsgUtils.setBotMsg(ding,1,3,workWechatMsgInfoMapper,workWechatMsgContextMapper);
                WorkWechatSendMsgUtils.sendMsg("CY0006",ding);
            }
        }
        //logger.debug(temp);
        WorkWechatSendMsgUtils.setBotMsg(temp,1,1,workWechatMsgInfoMapper,workWechatMsgContextMapper);
    }

    //---------------------智能推送配置表推送

}
